import * as React from 'react'
import { Button, Input, InputRef, Tag, Tooltip } from 'antd'

export interface Props {
    value?: string[]
    onChange?: (value?: string[]) => void
}
export default (props: Props) => {
    const { onChange } = props
    const [editing, setEditing] = React.useState(false)
    const value: string[] = (props.value && props.value.toString() || '').match(/[^,]+/g) || []
    const ref = React.useRef<InputRef>()
    return <React.Fragment>
        {value.map((v, i) => <Tag key={i} >{v} &nbsp;<a onClick={() => {
            onChange(
                value.filter((a) => a != v)
            )
        }}>&times;</a></Tag>)}
        {editing ? <Input placeholder="输入选项" ref={ref} onBlur={(e) => {
            e.target.value && onChange(value.concat(e.target.value))
            setEditing(false)
        }} onKeyDown={e => {
            if (e.key === 'Enter') {
                let v = e.target['value']
                onChange(value.concat(v))
                if (ref.current?.input) {
                    ref.current.input.value = ''
                }
            }
        }}/> : <Tooltip title="点击新增">
            <Button type="link" onClick={() => setEditing(true)}>+</Button>
        </Tooltip>}
    </React.Fragment>
}